<template>
  <div style="width: 60%; margin: 10px auto">
    <div style="margin-bottom: 20px">
      <el-input v-model="data.title" size="large" style="width: 500px; margin-right: 10px" placeholder="请输入帖子标题"></el-input>
      <el-button size="large" type="primary" @click="load">搜索</el-button>
      <el-button size="large" type="info" @click="reset">重置</el-button>
      <el-button size="large" style="margin-left: 50px" type="primary" plain @click="handleCreatePost">发布帖子</el-button>
    </div>

    <div style="margin: 20px 0">
      <div class="card" v-for="post in data.postList" :key="post.id" style="margin-bottom: 10px; padding: 20px; cursor: pointer" @click="router.push('/front/postDetail?id=' + post.id)">
        <div style="display: flex; gap: 20px">
          <img :src="post.image" style="width: 150px; height: 150px">
          <div style="flex: 1">
            <div style="margin-bottom: 10px; font-size: 20px; font-weight: 500">{{ post.title }}</div>
            <div class="content-preview" v-html="truncatedContent(post.content)"></div>
            <div style="display: flex; align-items: center; color: #666">
              <img :src="post.userAvatar" style="width: 25px; height: 25px; border-radius: 50%">
              <span>{{post.userName}}</span>
              <el-icon color="#666" style="margin-left: 30px"><View></View></el-icon>
              <span style="margin-left: 5px">{{ post.viewCount }}</span>
              <el-icon color="#666" style="margin-left: 30px"><Clock></Clock></el-icon>
              <span style="margin-left: 5px">{{ post.createTime }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div style="margin: 20px 0" v-if="data.total">
      <el-pagination
          @current-change="load"
          @size-change="handleSizeChange"
          background
          layout="total, prev, pager, next, jumper, sizes"
          :page-sizes="[1, 3, 5, 10, 15, 20, 30]"
          :page-size="data.pageSize"
          v-model:current-page="data.pageNum"
          :total="data.total"
      />
    </div>

    <!--帖子信息-->
    <el-dialog title="帖子信息" v-model="data.formVisible" width="50%" destroy-on-close>
      <el-form ref="formRef" :model="data.form" :rules="data.rules" label-width="90px" style="padding: 20px">
        <el-form-item prop="title" label="帖子标题">
          <el-input v-model="data.form.title" placeholder="请输入帖子标题"></el-input>
        </el-form-item>
        <el-form-item prop="image" label="帖子图片">
          <el-upload
              :action="baseUrl + '/files/upload'"
              :headers="{ 'token': data.user.token }"
              :on-success="handleFileUpload"
              list-type="picture"
          >
            <el-button type="primary">上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item prop="content" label="帖子内容">
          <div style="border: 1px solid #ccc; width: 100%">
            <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :mode="mode"
            />
            <Editor
                style="height: 500px; overflow-y: hidden;"
                v-model="data.form.content"
                :mode="mode"
                :defaultConfig="editorConfig"
                @onCreated="handleCreated"
            />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="createPost">确 定</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
  import { reactive,ref,onBeforeUnmount, shallowRef } from "vue";
  import request from "@/utils/request.js";
  import { ElMessage } from "element-plus";
  import {Clock, View} from "@element-plus/icons-vue";
  import router from "@/router/index.js";
  import {Editor, Toolbar} from "@wangeditor/editor-for-vue";
  import '@wangeditor/editor/dist/css/style.css'

  const baseUrl = import.meta.env.VITE_BASE_URL
  const formRef = ref()

  const data = reactive({
    user: JSON.parse(localStorage.getItem('xm-user') || '{}'),
    pageNum: 1,
    pageSize: 10,
    title: null,
    postList: [],
    total: 0,
    form: null,
    formVisible: false,
    rules: {
      title: [
        { required: true, message: '请输入标题', trigger: ['blur', 'change'] }
      ],
      content: [
        { required: true, message: '请输入内容', trigger: ['blur', 'change'] }
      ],
      image: [
        { required: true, message: '请上传封面', trigger: ['blur', 'change'] }
      ],
    }
  })

  /* wangEditor5 初始化开始 */
  const editorRef = shallowRef()  // 编辑器实例，必须用 shallowRef
  const mode = 'default'
  const editorConfig = { MENU_CONF: {} }
  // 图片上传配置
  editorConfig.MENU_CONF['uploadImage'] = {
    headers: {
      token: data.user.token,
    },
    server: baseUrl + '/files/wang/upload',  // 服务端图片上传接口
    fieldName: 'file'  // 服务端图片上传接口参数
  }
  // 组件销毁时，也及时销毁编辑器，否则可能会造成内存泄漏
  onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
  })
  // 记录 editor 实例，重要！
  const handleCreated = (editor) => {
    editorRef.value = editor
  }
  /* wangEditor5 初始化结束 */

  const handleFileUpload = (res) => {
    data.form.image = res.data
  }

  const load = () => {
    request.post('/post/pageQuery/forum', {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      title: data.title
    }).then(res => {
      if (res.code === '200') {
        data.postList = res.data?.list || []
        data.total = res.data?.total || 0
      } else {
        ElMessage.error(res.msg)
      }
    })
  }

  const reset = () => {
    data.title = null
    load()
  }

  const handleSizeChange = (newSize) => {
    data.pageSize = newSize
    data.pageNum = 1
    load()
  }

  load()

  const handleCreatePost = () => {
    data.formVisible = true
    data.form = {}
  }

  const createPost = () => {
    formRef.value.validate(valid => {
      if (valid) {
        request.post('/post/create', {
          title: data.form.title,
          content: data.form.content,
          image: data.form.image
        }).then(res => {
          if (res.code === '200') {
            ElMessage.success('发布成功')
            data.formVisible = false
            load()
          } else {
            ElMessage.error(res.msg)
          }
        })
      } else {
        ElMessage.warning('请输入请填写完')
      }
    })
  }

  // 处理富文本内容
  const truncatedContent = (html) => {
    const div = document.createElement('div')
    div.innerHTML = html

    // 过滤规则
    const allowedTags = ['p', 'ul', 'li', 'strong', 'em']
    const elements = Array.from(div.children)

    let preview = ''
    elements.slice(0, 3).forEach(el => {
      const tagName = el.tagName.toLowerCase()
      if (allowedTags.includes(tagName)) {
        // 特殊处理列表标签
        if (tagName === 'ul') {
          preview += `<div>${el.innerHTML}</div>`  // 将ul转换为div包裹
        } else {
          preview += el.outerHTML
        }
      }
    })

    return preview || '暂无内容预览'
  }
</script>

<style scoped>
.content-preview {
  display: -webkit-box;
  -webkit-box-orient: vertical;
/*  -webkit-line-clamp: 3;*/
  overflow: hidden;
  text-overflow: ellipsis;
  max-height: 4.5em;
  line-height: 1.5;
  font-size: 15px;
  color: #666;
  margin-bottom: 20px;
}

.content-preview ::v-deep(ul) {
  padding-left: 1.2em;
  margin: 0.5em 0;
  list-style-type: disc;
}

.content-preview ::v-deep(li) {
  margin: 0.2em 0;
}

.content-preview ::v-deep(strong) {
  font-weight: 600;
}
</style>